package com.zzcoder.mall.security.component;

import com.zzcoder.mall.common.dto.ResponseResult;
import com.zzcoder.mall.common.util.JsonUtil;
import com.zzcoder.mall.security.util.JwtUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
public class AuthenticationSuccessHandlerImpl implements AuthenticationSuccessHandler {
    @Value("${secure.jwt.tokenHead}")
    private String tokenHead;
    private JwtUtil jwtUtil;

    public AuthenticationSuccessHandlerImpl(JwtUtil jwtUtil) {
        this.jwtUtil = jwtUtil;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //登录成功后获取当前登录用户
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        response.setContentType("application/json;charset=utf-8");
        Map<String, Object> map = new HashMap<>();
        map.put("token", jwtUtil.generateToken(userDetails));
        map.put("tokenHead", tokenHead);
        PrintWriter out = response.getWriter();
        out.write(JsonUtil.toJSON(ResponseResult.success(map)));
        out.flush();
        out.close();
    }
}